﻿using ABCNet.Extensions;
using ABCNet.Notices.Dto;
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ABCNet.Notices
{
    /// <summary>
    /// 公告信息
    /// </summary>
    public class NoticeAppService : ABCNetAppServiceBase
    {
        private readonly IRepository<Notice> _repository;

        public NoticeAppService(IRepository<Notice> repository)
        {
            _repository = repository;
        }

        /// <summary>
        /// 查询公告明细分页
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<NoticeDto>> GetPageList(PagedSortedRequestInput input)
        {
            var query = _repository.GetAll().OrderByDescending(x => x.IsTop).ThenByDescending(x => x.TopTime).ThenByDescending(x => x.CreationTime);
            var pageList = await query.GetPageSortListAsync<Notice, NoticeDto>(input);
            return pageList;
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<int> Save(NoticeDto input)
        {
            Notice obj;
            if (input.Id == 0)
            {
                obj = input.MapTo<Notice>();
            }
            else
            {
                obj = _repository.Get(input.Id);
                obj.Content = input.Content;
                obj.IsTop = input.IsTop;
                obj.Title = input.Title;
            }
            if (input.IsTop)
                obj.TopTime = DateTime.Now;
            else
                obj.TopTime = new DateTime(2000, 1, 1);

            int id = await _repository.InsertOrUpdateAndGetIdAsync(obj);
            return id;
        }

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public NoticeDto GetDetail(EntityDto input)
        {
            var obj = _repository.Get(input.Id);
            var m = obj.MapTo<NoticeDto>();
            return m;
        }

        /// <summary>
        /// 删除公告
        /// </summary>
        /// <param name="input"></param>
        public int DeleteNotice(EntityDto input)
        {
            _repository.Delete(input.Id);
            return 1;
        }

    }
}
